package main

import (
	"asystem/control"
	"asystem/db"
	"fmt"
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/redis"
	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure"
	"strconv"
)

const (
	HTTPS = true
	HTTP  = false
)

// go:embed static/*
//var Static embed.FS

////go:embed view/*
//var Template embed.FS

func main() {
	if err := db.InitDb(); err != nil {
		fmt.Println("=========================== 初始化 mysql 数据库连接失败", err)
		return
	}

	if err := db.ConnRedis(); err != nil {
		fmt.Println("=========================== redis 数据库连接失败", err)
		return
	}

	if err := GinHttps(HTTP); err != nil {
		fmt.Println("=========================== 启动 web 服务失败，错误：", err)
	}
}

func GinHttps(isHttps bool) error {
	control.R = gin.Default()
	// 注册静态文件服务
	/*
		control.R.Any("/static/*filepath", func(c *gin.Context) {
			staticServer := http.FileServer(http.FS(Static))
			staticServer.ServeHTTP(c.Writer, c.Request)
		})
		control.R.SetHTMLTemplate(template.Must(template.New("").ParseFS(Static, "static/template/*")))
	*/

	// todo 该注释不能删
	control.R.LoadHTMLGlob("./view/**/*")
	control.R.Static("/static/", "./static")

	// 设置 session 使用 redis 存储
	store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("lianli"))
	//store.Options(sessions.Options{MaxAge: int(10 * time.Second), Path: "/admin"})
	store.Options(sessions.Options{MaxAge: 14400, Path: "/"})
	//store.Options(sessions.Options{MaxAge: 1800, Path: "/admin"})
	control.R.Use(sessions.Sessions("LIANLISESSIONID20220603", store))

	// 路由
	control.Routers()

	// 如果为 true 则注册 https 服务
	if isHttps {
		control.R.Use(TlsHandler(8080))
		return control.R.RunTLS(":"+strconv.Itoa(8080), "./keys/test.pem", "./keys/test.key")
	}
	return control.R.Run(":" + strconv.Itoa(8080))
}

func TlsHandler(port int) gin.HandlerFunc {
	return func(c *gin.Context) {
		secureMiddleware := secure.New(secure.Options{
			SSLRedirect: true,
			SSLHost:     ":" + strconv.Itoa(port),
		})
		err := secureMiddleware.Process(c.Writer, c.Request)
		if err != nil {
			fmt.Println(err, "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
			return
		}
		c.Next()
	}
}
